import { useSize } from 'ahooks';
import { Button, App } from 'antd';
import { Header } from 'antd/es/layout/layout';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';

import { AppStatusEnum } from '@/common/app/constants';
import PagesHeader from '@/components/pages-header';
import Back from '@/components/router/Back';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRouter } from '@/router/hooks';
import { useManagePage } from '@/store/configStore';
import { useDatasetStore } from '@/store/datasetStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useShareLinkActions } from '@/store/sharelinkStore';
import { Sharelink } from '@/types/share-link';

import ShareLinkModal from './components/SharelinkModal';
import ShareLinksTable from './components/SharelinksTable';
import './styles/share-link.scss';

const SharelinkPage = () => {
  const { message } = App.useApp();
  const router = useRouter();
  const managePage = useManagePage();
  const { isPc } = useWindowWidth();
  const [editShareLinkModal, setEditShareLinkModal] = useState(false);
  const [currentEditRow, setCurrentEditRow] = useState<Sharelink | undefined>(undefined);
  const { loadAllDatasets } = useDatasetStore();
  const { setShareLink } = useShareLinkActions();
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);
  const { t } = useTranslation();

  const handleEditRow = (link: Sharelink) => {
    setEditShareLinkModal(true);
    setCurrentEditRow(link);
  };

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';
  // const isPreview = queryParams.get('preview') === 'true';
  const { isPreview, reviewStatus } = useOrchestrationStore();

  useEffect(() => {
    setShareLink([]);
    loadAllDatasets({
      parentId: '',
      app_id: appId,
      isPage: false,
    });
  }, [appId, loadAllDatasets, setShareLink]);

  return (
    <div ref={ref} className="share-link h-full w-full overflow-hidden rounded-[12px] bg-[#FFFFFF]">
      {!isPc && (
        <Header style={{ background: '#FBFCFF', padding: 0, borderBottom: '1px solid #DDE5FF' }}>
          <div className="flex items-center">
            <div className="flex">
              <Back
                title="返回"
                onClick={() => {
                  router.push(managePage);
                }}
              />
            </div>
          </div>
        </Header>
      )}
      <div className="flex h-full flex-col">
        <div className="flex items-center">
          <div className="flex flex-col pb-5">
            <PagesHeader>分享链接</PagesHeader>
            <span className="ml-5 mt-[2px] text-cn-14 text-text-3">
              可以直接分享知识库给其他用户进行对话，对方无需登录既可直接进行对话。
            </span>
          </div>
          <div className="ml-auto mr-5">
            {!isPreview ? (
              <Button
                style={{ color: '#1B6DFA', border: '1px solid #1B6DFA' }}
                onClick={() => {
                  if (reviewStatus === AppStatusEnum.pass) {
                    setEditShareLinkModal(true);
                  } else if (reviewStatus === AppStatusEnum.pending) {
                    message.info(t('page.shareLink.review_pending'));
                  } else if (reviewStatus === AppStatusEnum.reject) {
                    message.info(t('page.shareLink.review_reject'));
                  } else {
                    message.info(t('page.shareLink.review_unpublished'));
                  }
                }}
              >
                创建分享链接
              </Button>
            ) : null}
          </div>
        </div>
        <div className="flex-1">
          <ShareLinksTable
            parentSize={size ?? { width: 0, height: 0 }}
            className="mx-[14px]"
            onEditRow={handleEditRow}
          />
        </div>
      </div>
      <ShareLinkModal
        open={editShareLinkModal}
        initialValues={currentEditRow}
        onCancel={() => {
          setCurrentEditRow(undefined);
          setEditShareLinkModal(false);
        }}
        title="创建分享链接"
      />
    </div>
  );
};

export default SharelinkPage;
